﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Cosmetic.Logic;
using Cosmetic.DataEntity;
using System.Collections;
using System.Data;

namespace WebApp.Management.Product
{
    public partial class AddOrderByRH : PageBase2
    {

        private ProductManager m_ProductManager = new ProductManager();
        private CommentManager m_CommentManager = new CommentManager();
        private BrandManager m_BrandManager = new BrandManager();
        private ProductSeriesManager m_SeriesManager = new ProductSeriesManager();
        private CategoryManager m_CategoryManager = new CategoryManager();
        SaleManager m_salemanager = new SaleManager();
        private RoleManager m_RoleManager = new RoleManager();
        private Order m_Order;

        private Cosmetic.DataEntity.Category m_Category = new Category();
        private Cosmetic.DataEntity.Category SaveFrontCategory = new Category();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.SignInUser1 == null)
            {
                Session.Remove("SignInUser1");
                this.ClientScript.RegisterStartupScript(this.GetType(), this.Title, "alert('请先登录权限!');window.top.location.href='/Management/indexs.aspx';", true);
                return;
            }
            if (!IsPostBack)
            {
                Cosmetic.DataEntity.User theUser = this.SignInUser1;
                if (!this.m_RoleManager.CheckUserRole(theUser, RoleManager.ERole.Admin))
                {
                    Session.Remove("SignInUser1");
                    this.ClientScript.RegisterStartupScript(this.GetType(), this.Title, "alert('你没有管理员权限!');window.top.location.href='/Management/indexs.aspx';", true);
                    return;
                }
            }
        }

        protected void Page_LoadComplete(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //string theCategoryId = this.Request.QueryString["CID"];
                //if (!string.IsNullOrEmpty(this.Request.QueryString["CID"]))
                //{
                //    lvProdust.DataSource = this.m_ProductManager.GetProductByCategory(new Guid(this.Request.QueryString["CID"]));
                //    lvProdust.DataBind();
                //}
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            BindProduct();
        }
        List<Cosmetic.DataEntity.Product> theProductList = null;
        private void BindProduct()
        {
            theProductList = new List<Cosmetic.DataEntity.Product>();
            if (this.txtProductCode.Text.Trim() != string.Empty)
            {
                theProductList = this.m_ProductManager.GetProductByProductCode(this.txtProductCode.Text.Trim());
                this.txtProductCode.Text = string.Empty;
            }
            else
            {
                theProductList = this.m_ProductManager.GetAll().OrderByDescending(theProduct => theProduct.CreateTime).ToList(); ;
            }

            this.lvProdust.DataSource = theProductList;
            this.lvProdust.DataBind();
        }

        protected void lvProdust_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                Cosmetic.DataEntity.Product theProduct = this.m_ProductManager.GetProductById(new Guid(e.CommandArgument.ToString()));
                if (e.CommandName.Equals("OnSelect"))
                {
                    this.txtProductName.Text = theProduct.Name;
                    this.txtPrice.Text = theProduct.eprice.ToString();
                    this.HFPID.Value = e.CommandArgument.ToString();
                }
                //else //if (e.CommandName.Equals("OnRecommend") || e.CommandName.Equals("OnFocus"))
                //{
                //    bool theIsExist = true;
                //  Cosmetic.DataEntity.RecommendProduct theRecommendProduct = m_ProductManager.GetRecommendProductByProductId(theProduct.ProductId);
                //    if (theRecommendProduct == null)
                //    {
                //        theRecommendProduct = new Cosmetic.DataEntity.RecommendProduct();
                //        theRecommendProduct.RecommendProductId = Guid.NewGuid();
                //        theIsExist = false;
                //    }
                //    theRecommendProduct.ProductId = theProduct.ProductId;
                //    theRecommendProduct.CreateTime = DateTime.Now;
                //    //新酒
                //    if (e.CommandName.Equals("OnRecommend"))
                //    {
                //        Session["id"] = e.CommandArgument.ToString();
                //        Response.Redirect("xinpro.aspx");
                //    }
                //    //热卖
                //    else if (e.CommandName.Equals("OnFocus"))
                //    {
                //        Session["id"] = e.CommandArgument.ToString();
                //        Response.Redirect("hotpro.aspx");
                //    }
                //    theRecommendProduct.UserId = this.SignInUser.UserId;
                //    if (!theIsExist)
                //    {
                //        this.m_ProductManager.AddRecommendProduct(theRecommendProduct);
                //    }
                //    else
                //    {
                //        this.m_ProductManager.Update();
                //    }
                //}
            }
        }

        protected void btnShow_Click(object sender, EventArgs e)
        {
            List<Cosmetic.DataEntity.Product> theProductList = new List<Cosmetic.DataEntity.Product>();
            if (this.txtProductCode.Text.Trim() != string.Empty)
            {
                theProductList = this.m_ProductManager.GetProductByProductCode(this.txtProductCode.Text.Trim());
            }
            this.lvProdust.DataSource = theProductList;
            this.lvProdust.DataBind();
        }

        protected void lvProdust_PagePropertiesChanged(object sender, EventArgs e)
        {
            this.BindProduct();
        }

        protected void lvProductnew_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (Session["buycart"] != null && (Session["buycart"] as Hashtable).Count != 0)
            {
                Hashtable ht = Session["buycart"] as Hashtable;

                string pid = (e.Item.FindControl("HFPid") as HiddenField).Value;
                Label lbcount = e.Item.FindControl("lbCount") as Label;

                if (lbcount != null)
                {
                    lbcount.Text = ht[pid].ToString();
                }

                //计算小计价格
                Literal lblSmallCount = e.Item.FindControl("SmallCountNew") as Literal;

                decimal uintprice = decimal.Parse((e.Item.FindControl("UnitPrice") as Literal).Text);
                int count = Convert.ToInt32(ht[pid].ToString());
                if (m_salemanager.CheckSaleProduct(pid) && count >= 2)
                {
                    lblSmallCount.Text = (uintprice * (count / 2) * 2 * m_salemanager.GetDiscountRatio() + (count % 2) * uintprice).ToString("F2");
                }
                else
                {
                    lblSmallCount.Text = (uintprice * count).ToString("F2");
                }
                //(e.Item.FindControl("lbName") as Label).Text += "(Sale，每2件打" + m_salemanager.GetDiscountRatio() * 10 + "折)";
                //累加总价
                //this.m_Price = m_Price + uintprice * count;//).ToString("F2");

                //显示尺寸
                if (Session["size"] != null && ((Hashtable)Session["size"]).Count != 0)
                {
                    if ((Session["size"] as Hashtable).Contains(pid))
                    {
                        //Label lbsize = e.Item.FindControl("lbSize") as Label;

                        //lbsize.Text = (Session["size"] as Hashtable)[pid].ToString() ;
                    }
                }
                //Label allprice = e.Item.FindControl("lbAllPrice") as Label;
                //allprice.Text = (double.Parse(allprice.Text) + uintprice * count).ToString();
            }
            else if (Session["bookcart"] != null && (Session["bookcart"] as Hashtable).Count != 0)
            {
                Hashtable ht = Session["bookcart"] as Hashtable;

                string pid = (e.Item.FindControl("HFPid") as HiddenField).Value;

                Label lbcount = e.Item.FindControl("lbCount") as Label;

                if (lbcount != null)
                {
                    lbcount.Text = ht[pid].ToString();
                }

                //计算小计价格
                Label lblSmallCount = e.Item.FindControl("SmallCountNew") as Label;

                decimal uintprice = decimal.Parse((e.Item.FindControl("UnitPrice") as Label).Text);
                int count = Convert.ToInt32(ht[pid].ToString());

                lblSmallCount.Text = (uintprice * count).ToString("F2");


                if (Session["size"] != null && ((Hashtable)Session["size"]).Count != 0)
                {
                    if ((Session["size"] as Hashtable).Contains(pid))
                    {
                        Label lbsize = e.Item.FindControl("lbSize") as Label;
                        lbsize.Text = (Session["size"] as Hashtable)[pid].ToString();
                    }
                }
            }
        }

        //提交定单。
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(hfMemberID.Value))
            { return; }
            string uid = hfMemberID.Value;

            m_Order = new Order();
            m_Order.PayType = this.ddlPayType.SelectedItem.Text;
            m_Order.Valid = false;

            // Session["PayType"] = m_Order.PayType;

            Hashtable theHashtable = null;
            Hashtable packageHashtable = null;
            if (Session["buycart"] != null)
            {
                theHashtable = Session["buycart"] as Hashtable;
            }

            if (Session["integral"] == null)
            {
                m_Order.Intergral = (m_Order.Price);// + Convert.ToDecimal(Session["DeliveryPrice"])
            }

            string city = "";// this.DDLProvince.SelectedItem.Text;
            m_Order.DeliveryType = "快递 ";
           // Session["DeliveryPrice"] = 0;//GetDeliveryPrive(city).ToString();
            m_Order.DeliveryUserName = this.txtReceive.Text.Trim();
            m_Order.DeliveryAddress = this.txtAddress.Text;// this.DDLProvince.SelectedItem.Text + this.DDLCity.SelectedItem.Text + this.txtAddress.Text.Trim();//this.DropDownList1.SelectedItem.Text+"  "+this.DropDownList2.SelectedItem.Text+"  "+this.txtDeliveryAddress.Text.Trim();
            m_Order.DeliveryPostCode = this.txtZIP.Text.Trim();
            m_Order.DeliveryTel = this.txtPhone.Text.Trim();
            m_Order.DeliveryCellPhone = this.txtPhone.Text.Trim();
            m_Order.adress1 = "";// this.DDLProvince.SelectedItem.Text;
            m_Order.adress2 = "";// this.DDLCity.SelectedItem.Text;
            m_Order.adress3 = "";// this.ddlArea.SelectedItem.Text;
            m_Order.adress4 = this.txtAddress.Text;
            m_Order.tel1 = "021";
            m_Order.tel2 = this.txtPhone.Text;
            m_Order.DeliveryAddress1 = "";// this.txtAddress1.Text;
            m_Order.DeliveryAddress2 = "";// this.txtAddress2.Text;
            m_Order.DeliveryPrice = 0;// Convert.ToDecimal(Session["DeliveryPrice"]);
            m_Order.User = null; //this.SignInUser;
            m_Order.SendDate = DateTime.Now;
            m_Order.OrderId = Guid.NewGuid();
            m_Order.User = m_UserManager.GetUserByName(this.txtReceive.Text);

            //if (string.IsNullOrEmpty(uid))
            //{
            //    this.ClientScript.RegisterStartupScript(this.GetType(), "Register Failed", "alert('该用户名已经注册!')", true);
            //    return;
            //}
            //m_Order.UserId = new Guid(uid);
            //生成订单
            PurchaseManager thePurchaseManager = new PurchaseManager();
            m_Order.CreateTime = DateTime.Now;
            m_Order.ExpressNum = this.ddlExpress.SelectedItem.Text;
            m_Order.month = DateTime.Now.Month;
            m_Order.AddressId = new Guid("f0241e6d-b0af-4911-bc45-af3688dad592");//user.Addresses[0].AddressId;
            m_Order.State = "未付款"; //状态：未付款、已付款、已发货、申请退款、已退款、完成
            m_Order.DeliveryPrice = decimal.Parse(this.labCarriage.Text);//Convert.ToDecimal(Session["DeliveryPrice"]);
            m_Order.CompleteTime = DateTime.Now;
            m_Order.Year = DateTime.Now.Year;
            m_Order.OrderNum = thePurchaseManager.CreateOrderNum();
            m_Order.allprice = Convert.ToDecimal(this.hfAllPay.Value);
            m_Order.Price = Convert.ToDecimal(this.hfAllPay.Value);// Convert.ToDecimal(this.lbAfterAllPrice.Text);
            m_Order.Remark = "非分销商";
            m_Order.Intergral = Convert.ToDecimal(this.hfAllPay.Value);
            m_Order.IsBook = false;
            m_Order.UseIntegral = 0;
            m_Order.UseCashCard = 0;
            m_Order.UseDiscountCard = 0;
            if (Session["size"] == null || ((Hashtable)Session["size"]).Count == 0)
            {
                thePurchaseManager.InsertOrder(m_Order, theHashtable);
            }
            else
            {
                thePurchaseManager.InsertOrder(m_Order, theHashtable, packageHashtable, (Hashtable)Session["size"]);
            }
            ClientScript.RegisterStartupScript(this.GetType(), "Register Failed", "alert('订单创建成功!')", true);
            //清除数据。
            this.hfMemberID.Value = "";
            this.txtReceive.Text = "";
            this.labIsMember.Text = "";
        }

        protected void txtConfirmOrder_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.txtCount.Text) || string.IsNullOrEmpty(txtPrice.Text))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "Register Failed", "alert('数量和单价不能为空!')", true);
                return;
            }
            this.hfAllPay.Value = (decimal.Parse(this.hfAllPay.Value) + decimal.Parse(this.txtCount.Text) * decimal.Parse(this.txtPrice.Text)).ToString();
            DataTable table;
            if (ViewState["byProduct"] == null)
            {
                table = CreateTable();
            }
            else
            {
                table = ViewState["byProduct"] as DataTable;
            }
            DataRow dr = table.NewRow();
            dr["pid"] = HFPID.Value;
            dr["pname"] = this.txtProductName.Text;
            dr["price"] = decimal.Parse(this.txtPrice.Text);
            dr["count"] = int.Parse(this.txtCount.Text);
            dr["allprice"] = decimal.Parse(this.txtPrice.Text) * int.Parse(this.txtCount.Text);
            table.Rows.Add(dr);
            ViewState["byProduct"] = table;

            this.lvProductnew.DataSource = ViewState["byProduct"] as DataTable;
            this.lvProductnew.DataBind();
        }

        private DataTable CreateTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("pid", typeof(string));
            dt.Columns.Add("pname", typeof(string));
            dt.Columns.Add("price", typeof(decimal));
            dt.Columns.Add("count", typeof(int));
            dt.Columns.Add("allprice", typeof(decimal));
            return dt;
        }
        private UserManager m_UserManager = new UserManager();
        /// <summary>
        ///  创建一个用户返回ID。
        /// </summary>
        /// <returns></returns>
        private string CreateUser()
        {
            //if (null != this.m_UserManager.GetUserByName(this.txtReceive.Text.Trim()))
            //{
            //    this.ClientScript.RegisterStartupScript(this.GetType(), "Register Failed", "alert('该用户名已经注册!')", true);
            //    return "";
            //}
            if (string.IsNullOrEmpty(this.txtReceive.Text.Trim()))
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "Register Failed", "alert('用户名不能为空!')", true);
                return "";
            }
            if (string.IsNullOrEmpty(this.txtPhone.Text.Trim()))
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), this.Title, "alert('手机/电话号码不能为空!');", true);
                return "";
            }
            if (txtPhone.Text.Length != 11)
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "Register Failed", "alert('手机号码为11位数字！请正确填写!')", true);
                return "";
            }

            //if (string.IsNullOrEmpty(this.txtMailBox.Text.Trim()))
            //{
            //    this.ClientScript.RegisterStartupScript(this.GetType(), this.Title, "alert('邮箱不能为空!');", true);
            //    return;
            //}
            //if (this.txtPassword.Text == "")
            //{
            //    this.ClientScript.RegisterStartupScript(this.GetType(), this.Title, "alert('密码不能为空!');", true);
            //    return;
            //}
            Cosmetic.Logic.UserManager manage = new UserManager();
            User muser = manage.GetUserByName(this.txtReceive.Text.Trim());
            if (muser != null)
            {
                this.labIsMember.Text = "公司会员";
                return muser.UserId.ToString();
            }
            else
            {
                User theNewUser = new User();
                theNewUser.UserId = Guid.NewGuid();
                theNewUser.Email = "";//this.txtMailBox.Text.Trim();
                theNewUser.UserName = this.txtReceive.Text.Trim();
                theNewUser.Password = "111111";//this.txtPassword.Text;
                theNewUser.tel = this.txtPhone.Text.Trim();
                theNewUser.HowToKnowIbeauty = "百度";
                theNewUser.Level = "普通会员";
                theNewUser.RegisterTime = DateTime.Now;
                theNewUser.Status = true;//非激活用户
                this.labIsMember.Text = "已注册成公司会员，登陆密码默认为111111";
                this.m_UserManager.Insert(theNewUser);
                return theNewUser.UserId.ToString();
            }
        }

        protected void btnGet_Click(object sender, EventArgs e)
        {
            if (this.txtAddress.Text.Contains(System.Configuration.ConfigurationManager.AppSettings["cityName"].ToString()))
            {
                this.labCarriage.Text = System.Configuration.ConfigurationManager.AppSettings["shanghai"].ToString();
            }
            else
            {
                this.labCarriage.Text = System.Configuration.ConfigurationManager.AppSettings["otherCity"].ToString();
            }
            //this.hfAllPay.Value = (decimal.Parse(this.labCarriage.Text) + decimal.Parse(hfAllPay.Value)).ToString();
            this.labAllPrice.Text = (decimal.Parse(this.labCarriage.Text) + decimal.Parse(hfAllPay.Value)).ToString();
        }

        protected void btnCheckMember_Click(object sender, EventArgs e)
        {
            hfMemberID.Value = CreateUser();
        }

    }//end class


}